#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json,os,re,rrdtool
import urllib.request
from pprint import pprint
from collections import Counter

def http_get():
    url='http://172.16.1.16:8008/activeflows/ALL/IXP/json?maxFlows=3000'
    response = urllib.request.urlopen(url)
    return response.read()

ret = http_get()
webdata=json.loads(ret.decode('utf-8'))
listAZ=[]
merge_dict={}

for n in webdata:
    temp_string=re.split('[,]',n['key'])
    strAZ=temp_string[2]+','+temp_string[3]
    dictAZ={strAZ:n['value']}
    listAZ.append(dictAZ)

for i in listAZ:
    x=Counter(i)
    y=Counter(merge_dict)
    merge_dict=(x+y)
      
for keys in merge_dict:
    str_A_Z=re.split('[,]',keys)
    strZA=str_A_Z[1]+','+str_A_Z[0]
    if os.path.isdir('/var/rra/%s' %str_A_Z[0]):
        pass
    else:
        os.system('mkdir /var/rra/%s' %str_A_Z[0])
    if os.path.isfile('/var/rra/%s/%s.rrd' %(str_A_Z[0],keys)):   
        rrdtool.update('/var/rra/%s/%s.rrd' %(str_A_Z[0],keys),
                       'N:%s:%s' %(merge_dict[keys],merge_dict[strZA]))
    else:
        rrdtool.create("/var/rra/%s/%s.rrd" %(str_A_Z[0],keys),
                       '--start','now',
                       '--step','60',
                       'DS:out:GAUGE:120:0:U',
                       'DS:in:GAUGE:120:0:U',
                       'RRA:AVERAGE:0.5:1:3000',
                       'RRA:AVERAGE:0.5:5:4200',
                       'RRA:AVERAGE:0.5:30:3000',
                       'RRA:AVERAGE:0.5:120:8000')
        rrdtool.update('/var/rra/%s/%s.rrd' %(str_A_Z[0],keys),
                       'N:%s:%s' %(merge_dict[keys],merge_dict[strZA]))